package com.irdstudio.efp.console.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.irdstudio.efp.console.service.dao.RateSchemeCfgDao;
import com.irdstudio.efp.console.service.dao.RateSchemeDetailDao;
import com.irdstudio.efp.console.service.domain.RateSchemeCfg;
import com.irdstudio.efp.console.service.domain.RateSchemeDetail;
import com.irdstudio.efp.console.service.facade.PrdInfoService;
import com.irdstudio.efp.console.service.facade.RateSchemeCfgService;
import com.irdstudio.efp.console.service.vo.PrdInfoVO;
import com.irdstudio.efp.console.service.vo.RateSchemeCfgVO;
import com.irdstudio.efp.console.service.vo.RateSchemeDetailVO;
import com.irdstudio.basic.framework.core.base.FrameworkService;
import  com.irdstudio.basic.framework.core.util.StringUtil;
import com.irdstudio.basic.framework.core.util.TimeUtil;
import com.irdstudio.basic.framework.core.util.UUIDUtil;

/**
 * <p>ServiceImpl: 利率方案配置表				<p>
 *
 * @author fuzm
 * @date 2018-05-08
 */
@Service("rateSchemeCfgService")
public class RateSchemeCfgServiceImpl implements RateSchemeCfgService, FrameworkService {

    private static Logger logger = LoggerFactory.getLogger(RateSchemeCfgServiceImpl.class);

    @Autowired
    private RateSchemeCfgDao rateSchemeCfgDao;

    @Autowired
    private RateSchemeDetailDao rateSchemeDetailDao;

    @Autowired
    private PrdInfoService prdInfoService;

    /**
     * 新增操作
     */
    public int insertRateSchemeCfg(RateSchemeCfgVO inRateSchemeCfgVo) {
        logger.debug("当前新增数据为:" + inRateSchemeCfgVo.toString());
        int num = 0;
        try {
            String schemeNo = UUIDUtil.getUUID();
            RateSchemeCfg rateSchemeCfg = new RateSchemeCfg();
            setInsertDefaultProperty(inRateSchemeCfgVo);
            beanCopy(inRateSchemeCfgVo, rateSchemeCfg);
            rateSchemeCfg.setSchemeNo(schemeNo);
            //如果点提交就加生效时间
            if (!StringUtil.isEmpty(inRateSchemeCfgVo.getStatus()) && "1".equals(inRateSchemeCfgVo.getStatus()))
                rateSchemeCfg.setEffictiveDate(TimeUtil.getCurrentDateTime());
            List<RateSchemeDetailVO> rateSchemeDetailVOList = inRateSchemeCfgVo.getRateSchemeDetailVOLIst();
            if (rateSchemeDetailVOList != null && rateSchemeDetailVOList.size() > 0) {

                for (int old = 0; old < rateSchemeDetailVOList.size(); old++) {
                    for (int compare = old + 1; compare < rateSchemeDetailVOList.size(); compare++) {
                        if ((rateSchemeDetailVOList.get(old).getSingleTermUnitMax() <= rateSchemeDetailVOList.get(compare).getSingleTermUnitMax())
                                && (rateSchemeDetailVOList.get(old).getSingleTermUnitMin() >= rateSchemeDetailVOList.get(compare).getSingleTermUnitMin())) {
                            logger.error("存在交叉!");
                            return -2;
                        } else if ((rateSchemeDetailVOList.get(old).getSingleTermUnitMax() >= rateSchemeDetailVOList.get(compare).getSingleTermUnitMin())
                                && (rateSchemeDetailVOList.get(old).getSingleTermUnitMin() < rateSchemeDetailVOList.get(compare).getSingleTermUnitMin())) {
                            logger.error("存在交叉!");
                            return -2;
                        }
                    }
                }

                //插入详细信息
                for (RateSchemeDetailVO rateSchemeDetailVO : inRateSchemeCfgVo.getRateSchemeDetailVOLIst()) {
                    if (rateSchemeDetailVO.getSingleTermUnitMax() > 1000000000 || rateSchemeDetailVO.getSingleTermUnitMin() > 1000000000)
                        return -3;
                    rateSchemeDetailVO.setSchemeNo(inRateSchemeCfgVo.getSchemeNo());
                    RateSchemeDetail rateSchemeDetail = new RateSchemeDetail();
                    setInsertDefaultProperty(rateSchemeDetailVO);
                    beanCopy(rateSchemeDetailVO, rateSchemeDetail);
                    rateSchemeDetail.setDetailId(UUIDUtil.getUUID());
                    rateSchemeDetail.setSchemeNo(schemeNo);
                    num += rateSchemeDetailDao.insertRateSchemeDetail(rateSchemeDetail);
                }
            } else {
                logger.error("利率明细不能为空!");
                return -1;
            }
            num = rateSchemeCfgDao.insertRateSchemeCfg(rateSchemeCfg);
        } catch (Exception e) {
            logger.error("新增数据发生异常!", e);
            num = -1;
        }
        logger.debug("当前新增数据条数为:" + num);
        return num;
    }

    /**
     * 删除操作
     */
    public int deleteByPk(RateSchemeCfgVO inRateSchemeCfgVo) {
        logger.debug("当前删除数据条件为:" + inRateSchemeCfgVo);
        int num = 0;
        try {
            RateSchemeCfg rateSchemeCfg = new RateSchemeCfg();
            beanCopy(inRateSchemeCfgVo, rateSchemeCfg);
            RateSchemeCfg temp = rateSchemeCfgDao.queryByPk(rateSchemeCfg);
            //检查产品依赖
            PrdInfoVO prdInfoVO = new PrdInfoVO();
            prdInfoVO.setRateSchemeId(temp.getSchemeNo());
            List<PrdInfoVO> prdInfoVOS = prdInfoService.queryPrdInfoByOthers(prdInfoVO);
            boolean hadPrd = (prdInfoVOS != null && prdInfoVOS.size() != 0);
            //只有待生效才能删除
            if (!StringUtil.isEmpty(temp.getStatus()) && "0".equals(temp.getStatus()) && !hadPrd) {
                num = rateSchemeCfgDao.deleteByPk(rateSchemeCfg);
                //删除详细信息
                RateSchemeDetail rateSchemeDetail = new RateSchemeDetail();
                setInsertDefaultProperty(rateSchemeDetail);
                rateSchemeDetail.setSchemeNo(inRateSchemeCfgVo.getSchemeNo());
                num += rateSchemeDetailDao.deleteByScheme(rateSchemeDetail);
            } else if (hadPrd)
                num = -2;
            else {
                num = -1;
            }
            /*int temp = this.queryPrdByPk(inRateSchemeCfgVo);
            if (temp<=0) {
			setUpdateDefaultProperty(inRateSchemeCfgVo);
			RateSchemeCfg rateSchemeCfg = new RateSchemeCfg();
			beanCopy(inRateSchemeCfgVo, rateSchemeCfg);
			num = rateSchemeCfgDao.deleteByPk(rateSchemeCfg);

            //删除详细信息
            RateSchemeDetail rateSchemeDetail = new RateSchemeDetail();
            setInsertDefaultProperty(rateSchemeDetail);
            rateSchemeDetail.setSchemeNo(inRateSchemeCfgVo.getSchemeNo());
            num += rateSchemeDetailDao.deleteByScheme(rateSchemeDetail);
            }
            else{
                num = -2;
            }*/
        } catch (Exception e) {
            logger.error("删除数据发生异常!", e);
            num = -1;
        }
        logger.debug("根据条件:" + inRateSchemeCfgVo + "删除的数据条数为" + num);
        return num;
    }


    /**
     * 更新操作
     */
    @SuppressWarnings("unchecked")
    public int updateByPk(RateSchemeCfgVO inRateSchemeCfgVo) {
        logger.debug("当前修改数据为:" + inRateSchemeCfgVo.toString());
        int num = 0;
        try {
            //先更新组信息
            RateSchemeCfg rateSchemeCfg = new RateSchemeCfg();
            setUpdateDefaultProperty(inRateSchemeCfgVo);
            beanCopy(inRateSchemeCfgVo, rateSchemeCfg);
            num = rateSchemeCfgDao.updateByPk(rateSchemeCfg);
            //先查询
            RateSchemeDetail rateSchemeDetail = new RateSchemeDetail();
            setInsertDefaultProperty(rateSchemeDetail);
            rateSchemeDetail.setSchemeNo(inRateSchemeCfgVo.getSchemeNo());

            //比较id是否存在，如果存在就替换，如果不存在就新增
            List<RateSchemeDetail> oldDtls = rateSchemeDetailDao.queryByschemeNo(rateSchemeDetail);
            List<RateSchemeDetailVO> temp = inRateSchemeCfgVo.getRateSchemeDetailVOLIst();
            List<RateSchemeDetail> newDtls = new ArrayList<>();
            if (temp != null && !temp.isEmpty()) {
                newDtls = (List<RateSchemeDetail>) beansCopy(temp, RateSchemeDetail.class);
            } else {
                logger.error("利率明细不能为空!");
                return -1;
            }
            if (oldDtls.isEmpty() && newDtls.isEmpty()) {
                return num;
            }
            //交集判断
            for (int old = 0; old < temp.size(); old++) {
                for (int compare = old + 1; compare < temp.size(); compare++) {
                    if ((temp.get(old).getSingleTermUnitMax() <= temp.get(compare).getSingleTermUnitMax())
                            && (temp.get(old).getSingleTermUnitMin() >= temp.get(compare).getSingleTermUnitMin())) {
                        logger.error("存在交叉!");
                        return -2;
                    } else if ((temp.get(old).getSingleTermUnitMax() >= temp.get(compare).getSingleTermUnitMin())
                            && (temp.get(old).getSingleTermUnitMin() < temp.get(compare).getSingleTermUnitMin())) {
                        logger.error("存在交叉!");
                        return -2;
                    }
                }
            }

            List<RateSchemeDetail> addDtlCodes = null; //新增的明细列表
            List<RateSchemeDetail> deleteDtlCodes = null; //删除的明细列表
            List<RateSchemeDetail> updateDtlCodes = null; //修改的明细列表
            if (oldDtls.isEmpty()) {
                for (RateSchemeDetail newDtl : newDtls) {
                    newDtl.setSchemeNo(inRateSchemeCfgVo.getSchemeNo());
                    newDtl.setLoginUserId(inRateSchemeCfgVo.getLoginUserId());
                    newDtl.setDetailId(UUIDUtil.getUUID());
                    setInsertDefaultProperty(newDtl);
                }
                addDtlCodes = newDtls; //如果旧的没有, 则所有新的岗位码都是新增的

            } else if (newDtls.isEmpty()) {
                deleteDtlCodes = oldDtls; //如果新的没有，则是删除所有旧的
            } else {
                //			在原数组没有的，新数组有的， 则是新增的
//			在新数组没有的，老数组有的， 则是删除的
                addDtlCodes = new ArrayList<RateSchemeDetail>();
                deleteDtlCodes = new ArrayList<RateSchemeDetail>();
                updateDtlCodes = new ArrayList<RateSchemeDetail>();
                int flag;
                for (RateSchemeDetail newDtl : newDtls) {
                    if (null == newDtl)
                        break;
                    //新数组的元素在老数组里面查找元素， 如果无，则是新增的
                    flag = 0;
                    for (RateSchemeDetail oldDtl : oldDtls) {
                        if (newDtl.getDetailId().equals(oldDtl.getDetailId())) {
                            flag++;
                            break;
                        }
                    }
                    newDtl.setSchemeNo(inRateSchemeCfgVo.getSchemeNo());
                    newDtl.setLoginUserId(inRateSchemeCfgVo.getLoginUserId());

                    if (flag == 0) {
                        newDtl.setDetailId(UUIDUtil.getUUID());
                        setInsertDefaultProperty(newDtl);
                        addDtlCodes.add(newDtl);
                    } else {
                        setUpdateDefaultProperty(newDtl);
                        updateDtlCodes.add(newDtl);
                    }
                }

                for (RateSchemeDetail oldDtl : oldDtls) {
                    //老数组的元素在新数组里面查找元素， 如果无，则是删除的
                    flag = 0;
                    for (int j = 0; j < newDtls.size(); j++) {
                        if (null == newDtls.get(j))
                            break;
                        if (oldDtl.getDetailId().equals(newDtls.get(j).getDetailId())) {
                            flag++;
                            break;
                        }
                    }
                    if (flag == 0) {
                        deleteDtlCodes.add(oldDtl);
                    }
                }
            }
            if (null != deleteDtlCodes && !deleteDtlCodes.isEmpty()) {
                for (RateSchemeDetail deleteDtlCode : deleteDtlCodes) {
                    num += rateSchemeDetailDao.deleteByPk(deleteDtlCode);
                }
            }
            if (null != addDtlCodes && !addDtlCodes.isEmpty()) {
                for (RateSchemeDetail addDtlCode : addDtlCodes) {
                    num += rateSchemeDetailDao.insertRateSchemeDetail(addDtlCode);
                }
            }
            if (null != updateDtlCodes && !updateDtlCodes.isEmpty()) {
                for (RateSchemeDetail updateDtlCode : updateDtlCodes) {
                    num += rateSchemeDetailDao.updateByPk(updateDtlCode);
                }
            }
        } catch (Exception e) {
            logger.error("修改数据发生异常!", e);
            num = -1;
        }
        logger.debug("根据条件:" + inRateSchemeCfgVo + "修改的数据条数为" + num);
        return num;
    }

    @Override
    public int setStatusByPk(RateSchemeCfgVO rateSchemeCfgVo) {
        logger.debug("当前修改数据为:" + rateSchemeCfgVo.toString());
        int num;
        try {
            //失效时判断是否有有效产品调用，如果有就不能失效
            if (rateSchemeCfgVo.getStatus() != null && rateSchemeCfgVo.getStatus().equals("2")) {
                //检查产品依赖
                PrdInfoVO prdInfoVO = new PrdInfoVO();
                prdInfoVO.setRateSchemeId(rateSchemeCfgVo.getSchemeNo());
                List<PrdInfoVO> prdInfoVOS = prdInfoService.queryPrdInfoByOthers(prdInfoVO);
                boolean hadPrd = (prdInfoVOS != null && prdInfoVOS.size() != 0);
                if (!hadPrd) {
                    RateSchemeCfgVO temp = new RateSchemeCfgVO();
                    temp.setSchemeNo(rateSchemeCfgVo.getSchemeNo());
                    //失效
                    temp.setStatus("02");
                    RateSchemeCfg rateSchemeCfg = new RateSchemeCfg();
                    beanCopy(rateSchemeCfgVo, rateSchemeCfg);
                    setUpdateDefaultProperty(rateSchemeCfg);
                    rateSchemeCfg.setExpiryDate(TimeUtil.getCurrentDateTime());
                    num = rateSchemeCfgDao.setStatusByPk(rateSchemeCfg);
                } else {
                    num = -2;
                }
            } else {
                RateSchemeCfg rateSchemeCfg = new RateSchemeCfg();
                beanCopy(rateSchemeCfgVo, rateSchemeCfg);
                setUpdateDefaultProperty(rateSchemeCfg);
                if (rateSchemeCfgVo.getStatus().equals("1"))
                    rateSchemeCfg.setEffictiveDate(TimeUtil.getCurrentDateTime());
                num = rateSchemeCfgDao.setStatusByPk(rateSchemeCfg);
            }
        } catch (Exception e) {
            logger.error("修改数据发生异常!", e);
            num = -1;
        }
        logger.debug("根据条件:" + rateSchemeCfgVo + "修改的数据条数为" + num);
        return num;
    }

    @Override
    public int queryPrdByPk(RateSchemeCfgVO rateSchemeCfgVo) {
        logger.debug("当前修改数据为:" + rateSchemeCfgVo.toString());
        int num;
        try {
            RateSchemeCfg rateSchemeCfg = new RateSchemeCfg();
            beanCopy(rateSchemeCfgVo, rateSchemeCfg);
            num = rateSchemeCfgDao.queryPrdByPk(rateSchemeCfg);
        } catch (Exception e) {
            logger.error("修改数据发生异常!", e);
            num = -1;
        }
        logger.debug("根据条件:" + rateSchemeCfgVo + "修改的数据条数为" + num);
        return num;
    }

    /**
     * 查询操作
     */
    public RateSchemeCfgVO queryByPk(RateSchemeCfgVO inRateSchemeCfgVo) {

        logger.debug("当前查询参数信息为:" + inRateSchemeCfgVo);
        try {
            RateSchemeCfg queryRateSchemeCfg = new RateSchemeCfg();
            beanCopy(inRateSchemeCfgVo, queryRateSchemeCfg);
            RateSchemeCfg queryRslRateSchemeCfg = rateSchemeCfgDao.queryByPk(queryRateSchemeCfg);
            if (Objects.nonNull(queryRslRateSchemeCfg)) {
                RateSchemeCfgVO outRateSchemeCfgVo = beanCopy(queryRslRateSchemeCfg, new RateSchemeCfgVO());
                logger.debug("当前查询结果为:" + outRateSchemeCfgVo.toString());
                return outRateSchemeCfgVo;
            } else {
                logger.debug("当前查询结果为空!");
            }
        } catch (Exception e) {
            logger.error("查询数据发生异常!", e);
        }
        return null;
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<RateSchemeCfgVO> queryAllValidByPage(RateSchemeCfgVO rateSchemeCfgVo) {
        logger.debug("当前查询本人所属法人机构 利率方案的参数信息为:");
        List<RateSchemeCfgVO> list = null;
        try {
            List<RateSchemeCfg> rateSchemeCfgs = rateSchemeCfgDao.queryAllValidByPage(rateSchemeCfgVo);
            logger.debug("当前查询本人所属法人机构 利率方案的结果集数量为:" + rateSchemeCfgs.size());
            pageSet(rateSchemeCfgs, rateSchemeCfgVo);
            list = (List<RateSchemeCfgVO>) beansCopy(rateSchemeCfgs, RateSchemeCfgVO.class);
        } catch (Exception e) {
            logger.error("数据转换出现异常!", e);
        }

        return list;
    }


    /**
     * 查询用户权限数据
     */
    @SuppressWarnings("unchecked")
    public List<RateSchemeCfgVO> queryAllOwner(RateSchemeCfgVO rateSchemeCfgVo) {

        logger.debug("当前查询本人所属数据信息的参数信息为:" + rateSchemeCfgVo);
        List<RateSchemeCfgVO> list = null;
        try {
            if (rateSchemeCfgVo.getCreateTimeRange()!=null&&rateSchemeCfgVo.getCreateTimeRange().size()>0
                    &&rateSchemeCfgVo.getCreateTimeRange().get(0)!=null&&rateSchemeCfgVo.getCreateTimeRange().get(1)!=null){
                rateSchemeCfgVo.setCreateTimeStart(rateSchemeCfgVo.getCreateTimeRange().get(0)+" 00:00:00");
                rateSchemeCfgVo.setCreateTimeEnd(rateSchemeCfgVo.getCreateTimeRange().get(1)+" 23:59:59");
            }


            List<RateSchemeCfg> rateSchemeCfgs = rateSchemeCfgDao.queryAllOwnerByPage(rateSchemeCfgVo);
            logger.debug("当前查询本人所属数据信息的结果集数量为:" + rateSchemeCfgs.size());
            pageSet(rateSchemeCfgs, rateSchemeCfgVo);
            list = (List<RateSchemeCfgVO>) beansCopy(rateSchemeCfgs, RateSchemeCfgVO.class);
        } catch (Exception e) {
            logger.error("数据转换出现异常!", e);
        }

        return list;

    }


    /**
     * 查询当前机构权限数据
     */
    @SuppressWarnings("unchecked")
    public List<RateSchemeCfgVO> queryAllCurrOrg(RateSchemeCfgVO rateSchemeCfgVo) {

        logger.debug("当前查询本人所属机构数据信息的参数信息为:");
        if (rateSchemeCfgVo.getCreateTimeRange()!=null&&rateSchemeCfgVo.getCreateTimeRange().size()>0
                &&rateSchemeCfgVo.getCreateTimeRange().get(0)!=null&&rateSchemeCfgVo.getCreateTimeRange().get(1)!=null){
            rateSchemeCfgVo.setCreateTimeStart(rateSchemeCfgVo.getCreateTimeRange().get(0)+" 00:00:00");
            rateSchemeCfgVo.setCreateTimeEnd(rateSchemeCfgVo.getCreateTimeRange().get(1)+" 23:59:59");
        }
        List<RateSchemeCfg> rateSchemeCfgs = rateSchemeCfgDao.queryAllCurrOrgByPage(rateSchemeCfgVo);
        logger.debug("当前查询本人所属机构数据信息的结果集数量为:" + rateSchemeCfgs.size());
        List<RateSchemeCfgVO> list = null;
        try {
            pageSet(rateSchemeCfgs, rateSchemeCfgVo);
            list = (List<RateSchemeCfgVO>) beansCopy(rateSchemeCfgs, RateSchemeCfgVO.class);
        } catch (Exception e) {
            logger.error("数据转换出现异常!", e);
        }

        return list;

    }


    /**
     * 查询当前机构及下属机构权限数据
     */
    @SuppressWarnings("unchecked")
    public List<RateSchemeCfgVO> queryAllCurrDownOrg(RateSchemeCfgVO rateSchemeCfgVo) {

        logger.debug("当前查询本人所属机构及以下数据信息的参数信息为:");
        if (rateSchemeCfgVo.getCreateTimeRange()!=null&&rateSchemeCfgVo.getCreateTimeRange().size()>0
                &&rateSchemeCfgVo.getCreateTimeRange().get(0)!=null&&rateSchemeCfgVo.getCreateTimeRange().get(1)!=null){
            rateSchemeCfgVo.setCreateTimeStart(rateSchemeCfgVo.getCreateTimeRange().get(0)+" 00:00:00");
            rateSchemeCfgVo.setCreateTimeEnd(rateSchemeCfgVo.getCreateTimeRange().get(1)+" 23:59:59");
        }
        List<RateSchemeCfg> rateSchemeCfgs = rateSchemeCfgDao.queryAllCurrDownOrgByPage(rateSchemeCfgVo);
        logger.debug("当前查询本人所属机构及以下数据信息的结果集数量为:" + rateSchemeCfgs.size());
        List<RateSchemeCfgVO> list = null;
        try {
            pageSet(rateSchemeCfgs, rateSchemeCfgVo);
            list = (List<RateSchemeCfgVO>) beansCopy(rateSchemeCfgs, RateSchemeCfgVO.class);
        } catch (Exception e) {
            logger.error("数据转换出现异常!", e);
        }

        return list;

    }
}
